using System;
using System.Threading.Tasks;
using VOL.Core.Utilities;
using VOL.demo.IRepositories;
using System.Collections.Generic;
using VOL.Entity.DomainModels;
using VOL.demo.IServices;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.SystemModels;
using System.Linq;

namespace VOL.demo.Services
{
    public partial class PurchaseOrderModelService
    {
        /// <summary>
        /// 分页查询进货订单
        /// </summary>
        public async Task<WebResponseContent> GetPurchaseOrderPageListAsync(
            int pageIndex, 
            int pageSize, 
            string orderCode = null, 
            int? status = null, 
            long? supplierId = null, 
            DateTime? orderDate = null)
        {
            try
            {
                var result = await repository.GetPurchaseOrderPageListAsync(
                    pageIndex, pageSize, orderCode, status, supplierId, orderDate);

                return new WebResponseContent
                {
                    Status = true,
                    Message = "查询成功",
                    Data = new
                    {
                        Data = result.Data,
                        TotalCount = result.TotalCount,
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        TotalPages = (int)Math.Ceiling((double)result.TotalCount / pageSize)
                    }
                };
            }
            catch (Exception ex)
            {
                return new WebResponseContent
                {
                    Status = false,
                    Message = $"查询失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 保存进货订单
        /// </summary>
        /// <param name="request">进货订单保存请求</param>
        /// <returns>保存结果</returns>
        public async Task<WebResponseContent> SavePurchaseOrderAsync(SavePurchaseOrderRequest request)
        {
            try
            {
                if (request?.PurchaseOrder == null)
                {
                    return new WebResponseContent
                    {
                        Status = false,
                        Message = "进货订单信息不能为空"
                    };
                }

                // 生成进货单号
                if (string.IsNullOrEmpty(request.PurchaseOrder.OrderCode))
                {
                    request.PurchaseOrder.OrderCode = GenerateOrderCode();
                }

                // 保存进货订单主表
                var saveModel = new SaveModel
                {
                    MainData = new Dictionary<string, object>
                    {
                        ["OrderCode"] = request.PurchaseOrder.OrderCode,
                        ["OrderDate"] = request.PurchaseOrder.OrderDate,
                        ["SupplierId"] = request.PurchaseOrder.SupplierId,
                        ["Contact"] = request.PurchaseOrder.Contact,
                        ["ContactPhone"] = request.PurchaseOrder.ContactPhone,
                        ["DeptId"] = request.PurchaseOrder.DeptId,
                        ["UserId"] = request.PurchaseOrder.UserId,
                        ["Status"] = request.PurchaseOrder.Status,
                        ["Remarks"] = request.PurchaseOrder.Remarks,
                        ["IsDel"] = 0, // 设置删除标识为0（未删除）
                        ["CreateDate"] = DateTime.Now
                    }
                };
                
                var mainResult = base.Add(saveModel);
                if (!mainResult.Status)
                {
                    return mainResult;
                }

                // 保存进货订单明细
                if (request.OrderItems != null && request.OrderItems.Count > 0)
                {
                    // 获取所有货品ID
                    var goodsIds = request.OrderItems.Select(item => item.GoodsId).Distinct().ToList();
                    
                    // 从货品信息表获取货品详细信息
                    var productService = AutofacContainerModule.GetService<IproductinformationmodelService>();
                    var products = await productService.GetProductsByIdsAsync(goodsIds);
                    var productDict = products.ToDictionary(p => p.Id, p => p);
                    
                    // 调试日志：记录获取到的货品信息
                    Console.WriteLine($"获取到 {products.Count} 个货品信息，货品ID: {string.Join(",", goodsIds)}");

                    // 将DTO转换为实体模型
                    var orderItems = request.OrderItems.Select(item => 
                    {
                        var product = productDict.ContainsKey(item.GoodsId) ? productDict[item.GoodsId] : null;
                        
                        return new PurchaseOrderItemModel
                        {
                            OrderCode = request.PurchaseOrder.OrderCode,
                            GoodsId = item.GoodsId,
                            GoodsCode = product?.goodsCode ?? "",
                            GoodsName = product?.goodsName ?? "",
                            SpecModel = product?.specModel ?? "",
                            UnitId = product?.UnitId,
                            ProductTypeId = product?.productTypeId,
                            PurchaseQty = (int)item.Quantity,
                            PurchasePrice = item.UnitPrice,
                            Amount = item.Amount.ToString(),
                            ItemRemarks = item.Remark,
                            IsDel = 0, // 设置删除标识为0（未删除）
                            CreateDate = DateTime.Now
                        };
                    }).ToList();

                    // 使用PurchaseOrderItemModelService保存明细
                    var itemService = AutofacContainerModule.GetService<IPurchaseOrderItemModelService>();
                    var itemResult = await itemService.AddItemsAsync(orderItems);
                    if (!itemResult)
                    {
                        return new WebResponseContent
                        {
                            Status = false,
                            Message = "保存进货订单明细失败"
                        };
                    }
                }

                return new WebResponseContent
                {
                    Status = true,
                    Message = "保存成功",
                    Data = new { OrderCode = request.PurchaseOrder.OrderCode }
                };
            }
            catch (Exception ex)
            {
                return new WebResponseContent
                {
                    Status = false,
                    Message = $"保存失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 生成进货单号
        /// </summary>
        /// <returns>进货单号</returns>
        private string GenerateOrderCode()
        {
            return $"PO{DateTime.Now:yyyyMMddHHmmss}";
        }
    }
}
